package com.mazaiting.course.service;

import com.mazaiting.course.domain.Response;
import com.mazaiting.course.exception.CustomException;
import com.mazaiting.course.exception.ExceptionEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/***
 * 登录服务
 * @author mazaiting
 * @datetime 2022/3/7
 */
@Service
public class LoginService {


    /**
     * 日志框架
     */
    private final Logger logger = LoggerFactory.getLogger(LoginService.class);

    public String getFilePath (){
        String path = null;
        try {
            path = ResourceUtils.getURL("classpath:").getPath();
            //本地开发输出/C:/Program Files/Apache Software Foundation/Tomcat 9.0/webapps/xxx/WEB-INF/classes/static/upload
            //部署到服务器输出/C:/Program%20Files/Apache%20Software%20Foundation/Tomcat%209.0/webapps/xxx/WEB-INF/classes/static/upload
            path = URLDecoder.decode(path,"utf-8");//处理空格转化为%20
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(Objects.isNull(path) || !path.contains("webapps/")){
//            throw new CustomException(ExceptionEnum.GET_TOMCAT_PATH);
//            return "F:/ceshi/webapps";
            return "/tmp/webapps";
        }
        logger.info("原始路径:"+path);
        int i = path.lastIndexOf("webapps/");
//        String filePath = path.substring(1, i)+ "webapps/";
        String filePath = path.substring(0, i)+ "webapps/";
        logger.info("tomcatFilePath:"+filePath);
        return filePath;
    }

    /**
     * 登录检测
     * @param username 用户名
     * @param password 密码
     */
    public  Response  login(String username, String password) {
        String filePath = this.getFilePath();
        File dataFile = new File(filePath, "data");
        if (!dataFile.exists()){
            dataFile.mkdir();
        }
        File file = new File(dataFile, username+".txt");
        if(!file.isFile()){
            throw new CustomException(ExceptionEnum.LOGIN_ERROR);
        }
        String psd = null;
        try (InputStream io = new FileInputStream(file);
             BufferedInputStream bio = new BufferedInputStream(io)){
            byte [] bys = new byte[1024];
            int len;
            if((len = bio.read(bys)) != -1){
                psd = new String(bys,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        if(!StringUtils.isEmpty(psd) && password.equals(psd)){
            return new Response(ExceptionEnum.LOGIN_SUCCESS);
        }else{
            return new Response(ExceptionEnum.LOGIN_ERROR);
        }
    }

    /**
     * register login   此处的加锁，感觉可能会出现并发，按理说少数并发不需要加锁 我加着玩 B格显的高一些
     * @param username 用户名
     * @param password 密码
     */
    public synchronized void register(String username, String password){

        String filePath = this.getFilePath();
        logger.info("register/tomcatFilePath:"+filePath);
        File dataFile = new File(filePath, "data");
        // 此处不能再resource地下查看或者创建文件夹，会出现问题
        if (!dataFile.isDirectory()){
            logger.info("register/file:文件创建成功");
            dataFile.mkdir();
        }
        // 创建用户名文件
        File file = new File(dataFile, username+".txt");
        // 若已经存在则 返回异常USERNAME_REPETITION(-105,"用户已经存在"),
        if(file.exists()){
            logger.info("register/login:用户名重复");
            throw new CustomException(ExceptionEnum.USERNAME_REPETITION);
        }
        try (OutputStream os = new FileOutputStream(file)){
            byte[] bytes = password.getBytes(StandardCharsets.UTF_8);
            os.write(bytes, 0, bytes.length);
            os.flush();
        } catch (Exception e) {
            logger.info("register/Exception:异常");
            throw new CustomException(ExceptionEnum.REGISTER_EXCEPTION);
        }

    }


}
